package com.cy.store.controller;


import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController//@Controller+@ResponseBody
@RequestMapping("users")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    //注册
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user)
    {
        userService.reg(user);
        return new JsonResult<>(OK);
    }


    //登录
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session)
    {
        User data = userService.login(username,password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        return new JsonResult<User>(OK,data);
    }

    //修改密码
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session)
    {
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session)
    {
        User data = userService.getByUid(getuidFromSession(session));
        return  new JsonResult<>(OK,data);
    }

    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(User user,HttpSession session)
    {
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }


    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE= 10*1024*1024;

    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }


    //MultipartFile接口是SpringMVC提供一个接口，这个接口为我们
    // 包装了获取文件类型的数据（任何类型的file都可以接受），springboot它
    //有整合了SpringMVC，只需要SPringBoot自动将传递给服务的文件数据赋值给这个参数
    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file") MultipartFile file)
    {
          //判断文件是否为空
        if (file.isEmpty())
        {
            throw new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE)
        {
            throw new FileSizeException("文件超出限制");
        }
        //判断文件的类型是发是我们规定的和后缀类型
        String contentType = file.getContentType();
        //如果集合包含某个元素则返回值true
        if(!AVATAR_TYPE.contains(contentType))
        {
            throw new FileTypeException("文件类型不支持");
        }
        //上传的文件../upload/文件。png
        String parent = session.getServletContext().getRealPath("upload");
        //File对象指向这个路径，File是否存在
        File dir = new File(parent);
        if(!dir.exists())//检测目录是否存在
        {
            dir.mkdir();//创建当前的目录
        }
        //获取到这个文件的名称,UUID工具来将生成一个新的字符串作为文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("OriginalFilename="+originalFilename);
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,filename);//是一个空文件
        //参数file中的数据写入到这个空文件中
        try {
            file.transferTo(dest);//将file文件中的数据写入到dest文件
        }catch (FileStateException e) {
            throw new FileUploadException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadException("文件读写异常");
        }
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        //返回头像的路径/upload/test.png
        String avatar = "/upload"+filename;
        userService.changeAvatar(uid,avatar,username);
        //返回用户头像的路径给前端页面，将来用于头像展示使用
        return new JsonResult<>(OK,avatar);
    }
}
